const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const httpProxy = require('http-proxy');
const app = new Koa();
const proxy = httpProxy.createProxyServer({});

app.use(bodyParser());

app.use(async (ctx) => {
  // 读取请求中的 proxy 字段
  const proxyOptions = ctx.request.body.proxy;
  
  if (proxyOptions && proxyOptions.target) {
    // 设置超时时间
    if (proxyOptions.timeout) {
      proxy.options.timeout = proxyOptions.timeout;
    }

    // 修改请求的 host 为目标地址的 host
    ctx.request.header.host = new URL(proxyOptions.target).host;
    
    // 代理请求到目标地址
    ctx.respond = false; // 禁止 Koa 默认的响应处理
    proxy.web(ctx.req, ctx.res, { target: proxyOptions.target, changeOrigin: true }, (e) => {
      if (e) {
        console.error('err', e);
        ctx.res.writeHead(500, { 'Content-Type': 'text/plain' });
        ctx.res.end('Proxy request failed');
      }
    });

    proxy.on('error', (error, req, res) => {
    	console.error('Proxy error:', error);
    	if (!res.headersSent) {
   	    res.writeHead(500, { 'Content-Type': 'text/plain' });
    	}
    	res.end('Proxy request failed with socket hang up');
    });
  } else {
    ctx.body = 'Missing proxy target in request body!';
  }
});

const port = 3000;
app.listen(port, () => {
  console.log(`Proxy server is running on http://localhost:${port}`);
});

